import {
  Controller,
  Get,
  Post,
  Body,
  Put,
  Delete,
  Param,
  Query,
  Logger,
  HttpException,
  HttpStatus,
  Header,
  ParseIntPipe,
  UseGuards,
  Req,
} from "@nestjs/common";
import { UserService } from "./user.service";
import { User } from "./user.entity";
import { ConfigService } from "@nestjs/config";
import type { CreateUserDto, UserQueryDto, UpdateUserDto } from "./dto";
import { Gender } from "../enum/gender.enum";
import { CreateUserPipe } from "./pipes/create-user.pipe";
import { AuthGuard } from "@nestjs/passport";
import { AdminGuard } from "../guards/admin.guard";
import { JwtGuard } from "../guards/jwt.guard";
import { CaslGuard } from "../guards/casl.guard";
import { Can } from "../decorators/casl.decorator";
import { Action } from "../enum/action.enum";
import { MailerService } from "@nestjs-modules/mailer";
// import { Logger } from "nestjs-pino";

/**
 * 用户控制器 - 处理用户相关的HTTP请求
 */
@Controller("user")
@UseGuards(JwtGuard, CaslGuard)
@Can(Action.READ, User)
export class UserController {
  private logger = new Logger(UserController.name);

  // 依赖注入：用户服务和配置服务
  constructor(
    private readonly userService: UserService,
    private readonly configService: ConfigService,
    private readonly mailerService: MailerService,
    // private readonly logger: Logger
  ) {
    this.logger.log("UserController initialized");
  }

  /**
   * 获取所有用户（支持分页、搜索、筛选）
   */
  @Get("page")
  findAll(
    @Query("page") page?: string,
    @Query("pageSize") pageSize?: string,
    @Query("search") search?: string,
    @Query("gender") gender?: string,
    @Query("roleId") roleId?: string,
  ) {
    const queryDto: UserQueryDto = {
      page: page ? parseInt(page, 10) : undefined,
      pageSize: pageSize ? parseInt(pageSize, 10) : undefined,
      search: search || undefined,
      gender: gender !== undefined && gender !== "" ? (gender as Gender) : undefined,
      roleId: roleId ? parseInt(roleId, 10) : undefined,
    };

    return this.userService.findAll(queryDto);
  }

  /**
   * 根据用户名查找用户
   * @param username 用户名
   */
  @Get("search")
  find(@Query("username") username: string) {
    return this.userService.find(username);
  }

  /**
   * 查询用户档案
   * @param id 用户ID
   */
  @Get("profile")
  findProfile(
    @Query("id", ParseIntPipe) id: number,
    // 这里 req 中的 user 是通过 AuthGuard("jwt") 中的 validate 方法返回的
    // PassportModule 来添加的
    @Req() req,
  ) {
    return this.userService.findProfile(id);
  }

  @Post("send-email")
  sendEmail(@Body("email") email: string, @Body("username") username?: string) {
    return this.mailerService
      .sendMail({
        to: email,
        from: "gaoshunpeng@foxmail.com",
        subject: "欢迎加入 learn-nestjs",
        template: "welcome",
        context: {
          title: "欢迎来到 learn-nestjs",
          appName: "learn-nestjs",
          name: username || "用户",
          actionUrl: `https://gitee.com/echo-52hz/learn-nestjs`,
          buttonText: "立即开始",
          extraNote: `如果无法点击按钮，可复制上方链接。你的验证码：${Math.random().toString(36).substring(2, 15).toUpperCase()}`,
          supportEmail: "gaoshunpeng@foxmail.com",
          year: new Date().getFullYear(),
          unsubscribeUrl: "https://gitee.com/echo-52hz/learn-nestjs",
        },
      })
      .then(() => {
        return "邮件发送成功";
      })
      .catch((e) => {
        throw new HttpException(e.message, HttpStatus.INTERNAL_SERVER_ERROR);
      });
  }

  /**
   * 根据id查找用户
   * @param id 用户id
   */
  @Get(":id")
  findOne(@Param("id") id: number) {
    return this.userService.findOne(id);
  }

  /**
   * 创建新用户
   * @param user 用户信息
   */
  @Post()
  @Can(Action.CREATE, User)
  create(@Body(CreateUserPipe) user: CreateUserDto) {
    return this.userService.create(user);
  }

  /**
   * 更新用户信息
   * @param id 用户ID
   * @param user 更新的用户信息
   */
  @Put(":id")
  @Can(Action.UPDATE, User)
  update(@Param("id") id: number, @Body() user: UpdateUserDto) {
    return this.userService.update(id, user);
  }

  /**
   * 删除用户
   * @param id 用户ID
   */
  @Delete(":id")
  @Can(Action.DELETE, User)
  remove(@Param("id") id: number) {
    return this.userService.remove(id);
  }
}
